package com.ruoyi.jacfile.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.file.JacMinioException;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.jacfile.domain.OrderModel;
import com.ruoyi.jacfile.domain.Order_test;
import com.ruoyi.jacfile.minio.MinIoService;
import com.ruoyi.jacfile.service.IJacFileInfoService;
import com.ruoyi.jacfile.service.IOrderModelService;
import com.ruoyi.jacfile.service.IOrderTestService;
import com.ruoyi.jacfile.util.ITextUtil;
import com.ruoyi.system.domain.JacFileInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/pdf")
public class ITextController extends BaseController {

    @Autowired
    private IJacFileInfoService jacFileInfoService;

    @Autowired
    private MinIoService minIoService;

    @Autowired
    private IOrderModelService orderModelService;

    @Autowired
    private IOrderTestService orderTestService;

    @ApiOperation(value = "pdfproduce",notes = "PDF生成并上传至Minio")
    @GetMapping("/produce")
    public R producepdf(Order_test order_test,String order_id) throws Exception {

        List<OrderModel> tab1 = orderModelService.selectOrderModelList1(order_id);
        List<OrderModel> tab2 = orderModelService.selectOrderModelList2(order_id);
        List<Order_test> order_tests = orderTestService.selectOrderTestList(order_test);
        String filepath = ITextUtil.pdfProduce(order_tests,tab1,tab2);

        String pdfMinioPath = "";
        try {
            minIoService.setMinioClient();
        } catch (Exception e) {
            throw new JacMinioException("file","minio连接失败");
        }
        try {
            pdfMinioPath = minIoService.minioUploadPdf(filepath);
        } catch (Exception e) {
//            throw new Exception(StringUtils.format("上传打印PDF文件出错，请联系管理员。 "));
            throw new JacMinioException("produce","上传打印PDF文件出错，请联系管理员。");
        }
        int i = pdfMinioPath.indexOf("/");
        JacFileInfo jacFileInfo = new JacFileInfo();
        jacFileInfo.setBucketname(pdfMinioPath.substring(0,i));
        jacFileInfo.setEncodename(pdfMinioPath.substring(i+1));
        jacFileInfo.setRealname(pdfMinioPath.substring(i+1));
        int i1 = jacFileInfoService.insertJacFileInfo(jacFileInfo);
        FileUtils.deleteFile(filepath);
        return toAjax(i1);

    }

    @GetMapping("/pdfdownload")
    public void pdfdownload(){

    }
}
